package com.coffee.takeoutserver.controller;

import com.coffee.takeoutserver.bean.User;
import com.coffee.takeoutserver.util.ResponseInfo;
import com.coffee.takeoutserver.service.UserService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("loginByPhone")
    @ResponseBody
    public String loginByPhone(String phone) {
        User user = userService.getUserByPhone(phone);
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            userService.addUser(user);
        }
        Gson gson = new Gson();
        ResponseInfo res = new ResponseInfo();
        res.setCode("0");
        res.setData(gson.toJson(user));
        return gson.toJson(res);
    }

    @RequestMapping("updateUser")
    @ResponseBody
    public String updateUser(@RequestBody User user) {
        userService.updateUser(user);
        Gson gson = new Gson();
        ResponseInfo res = new ResponseInfo();
        res.setCode("0");
        res.setData("success");
        return gson.toJson(res);
    }

    @RequestMapping("loginByPhoneAndPassword")
    @ResponseBody
    public String loginByPhoneAndPassword(String phone, String password) {
        User user = userService.loginByPhoneAndPassword(phone, password);
        Gson gson = new Gson();
        ResponseInfo res = new ResponseInfo();
        res.setCode("0");
        res.setData(gson.toJson(user));
        return gson.toJson(res);
    }
}
